package com.zhijian.warehouse.manage.service.impl;

import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.collection.CollectionUtil;
import com.zhijian.autoconfigure.cache.CacheClient;
import com.zhijian.util.BeanUtil;
import com.zhijian.util.EncryptUtil;
import com.zhijian.util.page.Page;
import com.zhijian.warehouse.manage.dao.UserMapper;
import com.zhijian.warehouse.manage.entity.po.User;
import com.zhijian.warehouse.manage.entity.po.UserGroup;
import com.zhijian.warehouse.manage.entity.po.UserRole;
import com.zhijian.warehouse.manage.entity.vo.request.RoleSearchVo;
import com.zhijian.warehouse.manage.entity.vo.request.UserSaveOrUpdateVo;
import com.zhijian.warehouse.manage.entity.vo.request.UserSearchVo;
import com.zhijian.warehouse.manage.entity.vo.response.RoleVo;
import com.zhijian.warehouse.manage.entity.vo.response.UserVo;
import com.zhijian.warehouse.manage.service.RoleService;
import com.zhijian.warehouse.manage.service.UserGroupService;
import com.zhijian.warehouse.manage.service.UserRoleService;
import com.zhijian.warehouse.manage.service.UserService;
import com.zhijian.warehouse.manage.util.AssertCommonUtil;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 人员业务处理层
 *
 * @author auto
 * @version: 1.0
 * @date 2024-10-09 16:34:28
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper mapper;
    
    /**
     * 默认登录密码
     */
    @Value("${default.password}")
    private String defaultPassword;
    
    @Autowired
    private UserRoleService userRoleService;
    
    @Autowired
    private UserGroupService userGroupService;
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private CacheClient cacheClient;
    
    private final String CACHE_KEY_USER_AUDIT = "user:%s:audit:pass";
    
    @Override
    public User selectByJobNumber(String jobNumber) {
        return mapper.selectByJobNumber(jobNumber);
    }
    
    @Override
    public User selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }
    
    @Override
    public UserVo selectVoById(Long id) {
        UserVo userVo = mapper.selectVoById(id);
        if (BeanUtil.isEmpty(userVo)) {
            setRoleInfo(userVo);
            List<Long> longs = userGroupService.selectGroupIdsByUserId(id);
            userVo.setGroupId(BeanUtil.isEmpty(longs) ? null : longs.get(0));
        }
        return userVo;
    }
    
    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }
    
    @Override
    public void deleteByIdList(List<Long> idList) {
        if (CollectionUtil.isEmpty(idList)) {
            return;
        }
        mapper.deleteByIdList(idList);
    }
    
    @Override
    public Long insert(User user) {
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdateTime(now);
        return mapper.insert(user) > 0 ? user.getId() : 0L;
    }
    
    @Override
    public Long insertSelective(User user) {
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdateTime(now);
        return mapper.insertSelective(user) > 0 ? user.getId() : 0L;
    }
    
    @Override
    public boolean update(User user) {
        Date now = new Date();
        user.setUpdateTime(now);
        return mapper.updateByPrimaryKey(user) != 0;
    }
    
    @Override
    public boolean updateByPrimaryKeySelective(User record) {
        Date now = new Date();
        record.setUpdateTime(now);
        return mapper.updateByPrimaryKeySelective(record) != 0;
    }
    
    @Transactional
    @Override
    public boolean save(UserSaveOrUpdateVo saveOrUpdateVo) {
        Integer count = this.count(UserSearchVo.builder()
                .jobNumber(saveOrUpdateVo.getJobNumber())
                .build());
        AssertCommonUtil.check(count > 0, "此工号已存在");
        saveOrUpdateVo.setUserName(saveOrUpdateVo.getName());
        AssertCommonUtil.check(BeanUtil.isEmpty(saveOrUpdateVo.getUserName()), "用户名不能为空");
        if (BeanUtil.isEmpty(saveOrUpdateVo.getName()))
            AssertCommonUtil.check(true, "姓名不能为空");
        saveOrUpdateVo.setNamePinYin(convertToPinyin(saveOrUpdateVo.getName()));
        count = this.count(UserSearchVo.builder()
                .userName(saveOrUpdateVo.getUserName())
                .build());
        AssertCommonUtil.check(count > 0, "此用户名已存在");
        String salt = EncryptUtil.salt();
        //密码加盐，形成最后真正的密码
        String finalPwd = EncryptUtil.password(defaultPassword, salt);
        User user = new User();
        BeanUtils.copyProperties(saveOrUpdateVo, user);
        user.setPassword(finalPwd);
        user.setSalt(salt);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        Long userId = mapper.insert(user) > 0 ? user.getId() : 0L;
        AssertCommonUtil.check(userId == 0, "保存失败");
        List<Long> roleIds = saveOrUpdateVo.getRoleIds();
        roleIds.forEach(roleId -> userRoleService.insert(UserRole.builder()
                .userId(userId)
                .roleId(roleId)
                .build()));
        //插入人员-组织关系表
        userGroupService.insert(UserGroup.builder()
                .userId(userId)
                .groupId(saveOrUpdateVo.getGroupId())
                .build());
        return true;
    }
    
    
    private String convertToPinyin(String hanzi) {
        try {
            StringBuilder pinyinBuilder = new StringBuilder();
            char[] characters = hanzi.toCharArray();
            for (char c : characters) {
                String[] pinyins = PinyinHelper.toHanyuPinyinStringArray(c);
                if (pinyins != null && pinyins.length > 0) {
                    // 取拼音的字母部分，不带音标
                    String pinyinWithoutTone = pinyins[0].replaceAll("[\\d]", "");
                    pinyinBuilder.append(pinyinWithoutTone); // 添加拼音
                }
            }
            return pinyinBuilder.toString(); // 返回拼音
        } catch (Exception e) {
            log.error("convertToPinyin error", e);
        }
        return null;
    }
    
    @Override
    public boolean resPassword(UserSaveOrUpdateVo param) {
        String salt = EncryptUtil.salt();
        //密码加盐，形成最后真正的密码
        String finalPwd = EncryptUtil.password(defaultPassword, salt);
        return this.updateByPrimaryKeySelective(User.builder()
                .id(param.getId())
                .password(finalPwd)
                .salt(salt)
                .build());
    }
    
    @Override
    public boolean updateAuditPass(UserSaveOrUpdateVo param) {
        User user = this.selectById(param.getId());
        AssertCommonUtil.check(BeanUtil.isEmpty(user), "此数据不存在或者已被删除");
        AssertCommonUtil.check(BeanUtil.isEmpty(param.getAuditPass()), "请输入审核密码");
        String salt = EncryptUtil.salt();
        //密码加盐，形成最后真正的密码
        String finalPwd = EncryptUtil.password(param.getAuditPass(), salt);
        if (!Objects.equals(user.getAuditPass(), finalPwd)) {
            cacheClient.del(String.format(CACHE_KEY_USER_AUDIT, user.getId()));
        }
        return this.updateByPrimaryKeySelective(User.builder()
                .id(param.getId())
                .auditPass(finalPwd)
                .auditSalt(salt)
                .build());
    }
    
    @Override
    public boolean checkAuditPass(UserSaveOrUpdateVo param) {
        AssertCommonUtil.check(BeanUtil.isEmpty(param.getAuditPass()), "请输入审核密码");
        User user = this.selectById(param.getId());
        String salt = user.getAuditSalt();
        //密码加盐，形成最后真正的密码
        String finalPwd = EncryptUtil.password(param.getAuditPass(), salt);
        boolean equals = Objects.equals(user.getAuditPass(), finalPwd);
        if (equals)
            cacheClient.set(String.format(CACHE_KEY_USER_AUDIT, user.getId()), "true", 10, TimeUnit.MINUTES);
        return equals;
    }
    
    @Override
    public boolean checkAuditPassTime(UserSaveOrUpdateVo param) {
        String auditPass = cacheClient.get(String.format(CACHE_KEY_USER_AUDIT, param.getId()));
        return !BeanUtil.isEmpty(auditPass);
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean modify(UserSaveOrUpdateVo saveOrUpdateVo) {
        User old = this.selectById(saveOrUpdateVo.getId());
        AssertCommonUtil.notNull(old, "此数据不存在或者已被删除");
        Long userId = saveOrUpdateVo.getId();
        Integer count = this.count(UserSearchVo.builder()
                .notId(userId)
                .jobNumber(saveOrUpdateVo.getJobNumber())
                .build());
        AssertCommonUtil.check(count > 0, "此工号已存在");
        count = this.count(UserSearchVo.builder()
                .notId(userId)
                .userName(saveOrUpdateVo.getUserName())
                .build());
        AssertCommonUtil.check(count > 0, "此用户名已存在");
        if (BeanUtil.isEmpty(saveOrUpdateVo.getName()))
            AssertCommonUtil.check(true, "姓名不能为空");
        
        saveOrUpdateVo.setNamePinYin(convertToPinyin(saveOrUpdateVo.getName()));
        old.setName(saveOrUpdateVo.getName());
        old.setUserName(saveOrUpdateVo.getUserName());
        old.setPhone(saveOrUpdateVo.getPhone());
        old.setStatus(saveOrUpdateVo.getStatus());
        old.setJobNumber(saveOrUpdateVo.getJobNumber());
        old.setSex(saveOrUpdateVo.getSex());
        old.setNote(saveOrUpdateVo.getNote());
        old.setEmail(saveOrUpdateVo.getEmail());
        old.setNamePinYin(saveOrUpdateVo.getNamePinYin());
        this.update(old);
        
        //删除人-部门关系表
        userGroupService.deleteByUserId(userId);
        //插入人员-组织关系表
        userGroupService.insert(UserGroup.builder()
                .userId(userId)
                .groupId(saveOrUpdateVo.getGroupId())
                .build());
        
        //删除角色-人员关系表
        userRoleService.deleteByUserId(userId);
        List<Long> roleIds = saveOrUpdateVo.getRoleIds();
        roleIds.forEach(roleId -> userRoleService.insert(UserRole.builder()
                .userId(userId)
                .roleId(roleId)
                .build()));
        
        return true;
    }
    
    @Override
    public UserVo selectOne(UserSearchVo userSearchVo) {
        return mapper.selectOne(userSearchVo);
    }
    
    @Override
    public Integer count(UserSearchVo userSearchVo) {
        //转换成小写
        if (BeanUtil.isNotEmpty(userSearchVo.getNameOrPinYin()))
            userSearchVo.setNameOrPinYin(userSearchVo.getNameOrPinYin().toLowerCase());
        return mapper.count(userSearchVo);
    }
    
    @Override
    public List<UserVo> selectList(UserSearchVo userSearchVo) {
        //转换成小写
        if (BeanUtil.isNotEmpty(userSearchVo.getNameOrPinYin()))
            userSearchVo.setNameOrPinYin(userSearchVo.getNameOrPinYin().toLowerCase());
        List<UserVo> userVoList = mapper.selectList(userSearchVo);
        if (CollectionUtil.isEmpty(userVoList)) {
            return Collections.emptyList();
        }
        userVoList.forEach(this::setRoleInfo);
        return userVoList;
    }
    
    @Override
    public List<UserVo> selectListMsg(UserSearchVo param) {
        return mapper.selectListMsg(param);
    }
    
    /**
     * 设置角色相关信息
     *
     * @param userVo
     */
    private void setRoleInfo(UserVo userVo) {
        if (BeanUtil.isEmpty(userVo))
            return;
        //角色id数组
        List<Long> roleIds = userRoleService.selectRoleIdListByUserId(userVo.getId());
        userVo.setRoleIds(roleIds);
        List<RoleVo> roleVos = roleService.selectList(RoleSearchVo.builder()
                .idList(roleIds)
                .build());
        if (CollectionUtil.isNotEmpty(roleVos)) {
            userVo.setRoleNames(String.join(",", roleVos.stream().map(RoleVo::getName).collect(Collectors.toList())));
        }
    }
    
    @Override
    public Page<UserVo> selectPage(UserSearchVo userSearchVo) {
        AssertCommonUtil.check(Objects.isNull(userSearchVo.getPageNum()) || Objects.isNull(userSearchVo.getPageSize()), "分页参数不能为空");
        //先直接查总数
        int count = count(userSearchVo);
        //分页
        Page<UserVo> page = new Page<>(true, count, userSearchVo.getPageNum(), userSearchVo.getPageSize());
        userSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<UserVo> responseVos = this.selectList(userSearchVo);
        page.setData(responseVos);
        return page;
    }
    
    @Override
    public boolean insertBatch(List<User> entities) {
        return CollectionUtil.isNotEmpty(entities) && mapper.insertBatch(entities) > 0;
    }
    
    @Override
    public boolean importExcel(MultipartFile file) {
        return false;
    }
    
    private <T> List<T> getVoList(int sheetNum, Class<T> pojoClass, String fileName) {
        ImportParams params = new ImportParams();
        params.setHeadRows(1); // 忽略第一行
        params.setTitleRows(0);
        params.setSheetNum(sheetNum);
        //return ExcelUtils.importExcel(FILE_PATH + fileName,  params,pojoClass);
        return null;
    }
}
